package leetcode.leetcode_36;

class Solution {
    public boolean isValidSudoku(char[][] board) {
        if (!checkRow1(board)){
            return false;
        }
        if (!checkCol1(board)){
            return false;
        }
        if (!checkMatrix1(board)){
            return false;
        }
        return true;
    }
//    1. 检查行满足条件不重复
    public boolean checkRow1(char[][] board){
        for(int i =0 ;i<9;i++){
            boolean [] flag = new boolean[10];
            for (int j =0;j<9;j++){
                if (board[i][j]!='.'){
                    if (flag[board[i][j]-'0']){
                        return false;
                    }
                    else flag[board[i][j]-'0'] = true;
                }
            }
        }
        return true;
    }
//    2. 检查列满足条件不重复
    public boolean checkCol1(char[][] board){
        for (int i =0;i<9;i++){
            boolean [] flag = new boolean[10];
            for (int j =0;j<9;j++){
                if (board[j][i]!='.'){
                    if (flag[board[j][i]-'0']){
                        return false;
                    }
                    else flag[board[j][i]-'0'] = true;
                }
            }
        }
        return true;
    }
//    3. 检查3*3矩阵满足条件不重复
    public boolean checkMatrix1(char[][] board){
        for (int i = 0 ;i<9;i+=3){
            for (int j = 0;j<9;j+=3){
            boolean [] flag = new boolean[10];
            for (int k = i;k<i+3;k++){
                for (int l = j;l<j+3;l++){
                    if (board[k][l]!='.'){
                        if (flag[board[k][l]-'0']){
                            return false;
                        }
                        else flag[board[k][l]-'0'] = true;
                    }
                }
            }
            }
        }
        return true;
    }
}